// ==================  配置  ==================
const GITEE_TOKEN = '17fc50b1c08c51a9c6c3013747d4b3c5';          // ①
const GITEE_REPO  = '郭余潇/照片墙信息';            // ② 私有仓库名（owner/repo）
const VAULT_KEY   = 'yuxiao123';         // ③ 用于加解密
// ==================  引入加密库  ==================
importScripts('https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/crypto-js.min.js');

// ==================  AuthManager 本体  ==================
class AuthManager {
    constructor() {
        this.currentUser = null;
        this.users = [];          // 初始空，后面异步拉
        this.init();
    }

    async init() {
        await this.loadUsers();   // 先拉远程
        this.checkAuthStatus();
        this.bindEvents();
    }

    /* ---------------------------------------------------- */
    /* 1. 加载用户（远程 → 解密 → 数组）                   */
    /* ---------------------------------------------------- */
    async loadUsers() {
        try {
            const url = `https://gitee.com/api/v5/repos/${GITEE_REPO}/contents/users.json`;
            const res = await fetch(url, { headers: { 'Authorization': `token ${GITEE_TOKEN}` } });
            if (!res.ok) throw '无文件';
            const { content } = await res.json();          // base64
            const cipherText  = atob(content);
            const plain       = CryptoJS.AES.decrypt(cipherText, VAULT_KEY).toString(CryptoJS.enc.Utf8);
            this.users = JSON.parse(plain);
        } catch (e) {
            this.users = [];   // 首次使用/文件不存在
        }
    }

    /* ---------------------------------------------------- */
    /* 2. 保存用户（加密 → 覆盖上传）                      */
    /* ---------------------------------------------------- */
    async saveUsers() {
        const cipherText = CryptoJS.AES.encrypt(JSON.stringify(this.users), VAULT_KEY).toString();
        const url = `https://gitee.com/api/v5/repos/${GITEE_REPO}/contents/users.json`;
        // 先拿 sha
        const shaRes = await fetch(url, { headers: { 'Authorization': `token ${GITEE_TOKEN}` } });
        const sha    = shaRes.ok ? (await shaRes.json()).sha : null;
        // 覆盖上传
        await fetch(url, {
            method : 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body   : JSON.stringify({
                message: 'update users',
                content: btoa(unescape(encodeURIComponent(cipherText))),
                sha
            })
        });
    }

    /* ---------------------------------------------------- */
    /* 3. 注册（本地校验 → 追加 → 上传）                   */
    /* ---------------------------------------------------- */
    async register(username, email, password) {
        // 1. 基础校验
        if (!username || !email || !password) throw '请填写所有必填字段';
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) throw '请输入有效的邮箱地址';
        if (password.length < 6) throw '密码长度至少为6位';
        // 2. 重名校验（拉最新）
        await this.loadUsers();
        if (this.users.find(u => u.username === username || u.email === email)) throw '用户名或邮箱已存在';
        // 3. 创建用户
        const newUser = {
            id: this.generateId(),
            username,
            email,
            password: this.hashPassword(password),
            avatar: 'resources/default-avatar.jpg',
            nickname: username,
            bio: '',
            joinDate: new Date().toISOString(),
            uploadedPhotos: [],
            favoritePhotos: [],
            likedPhotos: []
        };
        this.users.push(newUser);
        // 4. 上传整表
        await this.saveUsers();
        // 5. 自动登录
        this.currentUser = newUser;
        localStorage.setItem('gallery_current_user', JSON.stringify(newUser));
        this.updateUI();
        return newUser;
    }

    /* ---------------------------------------------------- */
    /* 4. 登录（拉最新 → 解密 → 比对）                     */
    /* ---------------------------------------------------- */
    async login(emailOrUsername, password) {
        await this.loadUsers();   // 实时拉
        const user = this.users.find(u => u.email === emailOrUsername || u.username === emailOrUsername);
        if (!user) throw '用户不存在';
        if (user.password !== this.hashPassword(password)) throw '密码错误';
        this.currentUser = user;
        localStorage.setItem('gallery_current_user', JSON.stringify(user));
        this.updateUI();
        return user;
    }

    logout() {
        this.currentUser = null;
        localStorage.removeItem('gallery_current_user');
        this.updateUI();
        if (window.location.pathname !== '/index.html' && window.location.pathname !== '/') {
            window.location.href = 'index.html';
        }
    }
    checkAuthStatus() {
        const saved = localStorage.getItem('gallery_current_user');
        if (saved) {
            const user = JSON.parse(saved);
            if (this.users.find(u => u.id === user.id)) this.currentUser = user;
            else localStorage.removeItem('gallery_current_user');
        }
        this.updateUI();
    }
    updateUI() {
        const userMenu = document.getElementById('user-menu');
        const loginBtn = document.getElementById('login-btn');
        const registerBtn = document.getElementById('register-btn');
        const userAvatar = document.getElementById('user-avatar');
        const username = document.getElementById('username');
        if (this.currentUser) {
            if (loginBtn) loginBtn.style.display = 'none';
            if (registerBtn) registerBtn.style.display = 'none';
            if (userMenu) userMenu.style.display = 'flex';
            if (userAvatar) userAvatar.src = this.currentUser.avatar;
            if (username) username.textContent = this.currentUser.nickname || this.currentUser.username;
        } else {
            if (loginBtn) loginBtn.style.display = 'inline-block';
            if (registerBtn) registerBtn.style.display = 'inline-block';
            if (userMenu) userMenu.style.display = 'none';
        }
    }
    bindEvents() {
        const loginForm = document.getElementById('login-form');
        if (loginForm) {
            loginForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const emailOrUsername = document.getElementById('login-email').value;
                const password = document.getElementById('login-password').value;
                try {
                    await this.login(emailOrUsername, password);
                    this.showMessage('登录成功！', 'success');
                    setTimeout(() => { location.href = 'index.html'; }, 1000);
                } catch (err) { this.showMessage(err, 'error'); }
            });
        }
        const registerForm = document.getElementById('register-form');
        if (registerForm) {
            registerForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const username = document.getElementById('register-username').value;
                const email = document.getElementById('register-email').value;
                const password = document.getElementById('register-password').value;
                const confirmPassword = document.getElementById('confirm-password').value;
                if (password !== confirmPassword) return this.showMessage('两次密码不一致', 'error');
                try {
                    await this.register(username, email, password);
                    this.showMessage('注册成功！', 'success');
                    setTimeout(() => { location.href = 'index.html'; }, 1000);
                } catch (err) { this.showMessage(err, 'error'); }
            });
        }
        const logoutBtn = document.getElementById('logout-btn');
        if (logoutBtn) logoutBtn.addEventListener('click', () => {
            this.logout();
            this.showMessage('已退出登录', 'info');
        });
        const userMenuBtn = document.getElementById('user-menu-btn');
        const userDropdown = document.getElementById('user-dropdown');
        if (userMenuBtn && userDropdown) {
            userMenuBtn.addEventListener('click', () => userDropdown.classList.toggle('hidden'));
            document.addEventListener('click', (e) => {
                if (!userMenuBtn.contains(e.target) && !userDropdown.contains(e.target)) userDropdown.classList.add('hidden');
            });
        }
    }
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }
    hashPassword(password) {
        let hash = 0;
        for (let i = 0; i < password.length; i++) {
            const char = password.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash;
        }
        return hash.toString();
    }
    showMessage(message, type = 'info') {
        const el = document.createElement('div');
        el.className = `fixed top-20 right-4 z-50 px-6 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-300 ${
            type === 'success' ? 'bg-green-500 text-white' :
            type === 'error' ? 'bg-red-500 text-white' :
            type === 'warning' ? 'bg-yellow-500 text-black' :
            'bg-blue-500 text-white'
        }`;
        el.textContent = message;
        document.body.appendChild(el);
        setTimeout(() => el.classList.remove('translate-x-full'), 100);
        setTimeout(() => {
            el.classList.add('translate-x-full');
            setTimeout(() => document.body.removeChild(el), 300);
        }, 3000);
    }
    getCurrentUser() { return this.currentUser; }
    isLoggedIn() { return this.currentUser !== null; }
    requireLogin() {
        if (!this.isLoggedIn()) {
            this.showMessage('请先登录', 'warning');
            setTimeout(() => { location.href = 'login.html'; }, 1000);
            return false;
        }
        return true;
    }
}

// 全局实例（自动初始化）
const authManager = new AuthManager();
// CommonJS 导出（Node 测试用）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AuthManager;
}